package com.yunhe.authority.service.authority.impl;

import com.yunhe.authority.domain.authority.HomePage;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.authority.repository.authority.HomePageRepository;
import com.yunhe.authority.service.authority.HomePageService;
import com.yunhe.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 首页对象Service
 * @author liuronglei
 */
@Service
public class HomePageServiceImpl implements HomePageService {
    @Autowired
    HomePageRepository homePageRepository;

    /**
     * 首页对象处理和判断
     * @param homePage 首页对象
     */
    private void processBeforeSave(HomePage homePage)
            throws ArgumentErrorException, UniqueConstraintsException {
        //判断首页编号、标题和Url是否为空
        if (StringUtil.isEmpty(homePage.getName())
                || StringUtil.isEmpty(homePage.getTitle())
                || StringUtil.isEmpty(homePage.getUrl())) {
            throw new ArgumentErrorException("首页编号、标题和URL不能为空");
        }
        //判断首页编号是否已存在
        HomePage homePageByName = this.findByName(homePage.getName());
        if (homePageByName != null) {
            if (homePage.getId() == null || homePageByName.getId().longValue() != homePage.getId().longValue()) {
                throw new UniqueConstraintsException("该首页编号已存在");
            }
        }
    }

    /**
     * 根据编号获得首页对象
     * @param name 首页编号
     */
    @Override
    public HomePage findByName(String name) {
        return homePageRepository.findByName(name);
    }

    /**
     * 新增首页对象
     * @param homePage 首页对象
     */
    @Override
    @Transactional
    public HomePage createHomePage(HomePage homePage)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        homePage.setId(null);
        processBeforeSave(homePage);
        return homePageRepository.save(homePage);
    }

    /**
     * 根据ID删除首页对象
     * @param homePageId 首页对象ID
     */
    @Override
    @Transactional
    public void deleteHomePage(Long homePageId) {
        homePageRepository.deleteById(homePageId);
    }

    /**
     * 更新首页对象（更新全部字段）
     * @param homePage 首页对象
     */
    @Override
    @Transactional
    public HomePage updateHomePage(HomePage homePage)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        boolean exists = homePage.getId() != null && homePageRepository.existsById(homePage.getId());
        if (!exists) {
            throw new ObjectNotFoundException("找不到ID为" + homePage.getId() + "的首页对象");
        }
        processBeforeSave(homePage);
        return homePageRepository.save(homePage);
    }

    /**
     * 更新首页对象（更新指定字段）
     * @param homePageId 首页ID
     * @param name 首页名
     * @param title 首页标题
     * @param url 首页Url
     * @param activity 是否可用
     */
    @Override
    @Transactional
    public HomePage updateHomePage(Long homePageId,
                                   String name,
                                   String title,
                                   String url,
                                   Boolean activity)
            throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        HomePage homePage = this.findByHomePageId(homePageId);
        if (homePage == null) {
            throw new ObjectNotFoundException("找不到ID为" + homePageId + "的首页对象");
        }
        Optional.ofNullable(name).ifPresent(homePage::setName);
        Optional.ofNullable(title).ifPresent(homePage::setTitle);
        Optional.ofNullable(url).ifPresent(homePage::setUrl);
        Optional.ofNullable(activity).ifPresent(homePage::setActivity);
        processBeforeSave(homePage);
        return homePageRepository.save(homePage);
    }

    /**
     * 根据ID获得首页对象
     * @param id 首页对象ID
     */
    @Override
    public HomePage findByHomePageId(Long id) {
        return homePageRepository.findById(id).orElse(null);
    }

    /**
     * 根据条件获得首页对象
     */
    @Override
    public Iterable<HomePage> findHomePages() {
        return homePageRepository.findAll();
    }

    /**
     * 根据用户ID获得首页对象
     * @param userId 用户ID
     */
    @Override
    public HomePage findHomePageByUserId(Long userId) {
        return homePageRepository.findHomePageByUserId(userId);
    }

    /**
     * 根据单位ID获得首页对象
     * @param firmId 单位ID
     */
    @Override
    public HomePage findHomePageByFirmId(Long firmId) {
        return homePageRepository.findHomePageByFirmId(firmId);
    }

}
